from model import db
from werkzeug.security import generate_password_hash


# 用户
class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    account = db.Column(db.String(256), nullable=False)
    _password = db.Column("password", db.String(512), nullable=False)
    username = db.Column(db.String(256), default="qia qia")
    gender = db.Column(db.String(20), default="man")

    # 自定义序列化
    def to_json(self):
        return {
            "id": self.id,
            "account": self.account,
            "password": self.password,
            "username": self.username,
            "gender": self.gender
        }

    # 属性包装 把方法当作属性一样使用
    @property
    def password(self):
        return self._password

    # user.password = xxxx
    @password.setter
    def password(self, value):
        self._password = generate_password_hash(value)

    @classmethod
    def create_user(cls, account, password, username='qia qia', gender='man'):
        user = cls()
        user.account = account
        user.password = password
        user.username = username
        user.gender = gender

        db.session.add(user)
        db.session.commit()


# 商品
class Commodity(db.Model):
    __tablename__ = "commodity"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(256), nullable=False)
    price = db.Column(db.Integer, nullable=False)
    address = db.Column(db.String(256), nullable=False)
    stock = db.Column(db.String(256), nullable=False)

    # 自定义序列化
    def to_json(self):
        return {
            "id": self.id,
            "name": self.name,
            "price": self.price,
            "address": self.address,
            "stock": self.stock
        }


# 购物车
class UserCommodityCart(db.Model):
    __tablename__ = "user_commodity_cart"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))  # 所属用户
    commodity_id = db.Column(db.Integer, db.ForeignKey("commodity.id"))  # 所含商品


# 订单
class UserCommodityOrder(db.Model):
    __tablename__ = "user_commodity_order"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))  # 所属用户
    commodity_id = db.Column(db.Integer, db.ForeignKey("commodity.id"))  # 所含商品


# 用户地址
class UserAddress(db.Model):
    __tablename__ = "user_address"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(256), nullable=False)  # 收件人
    phone = db.Column(db.String(11), nullable=False)
    address = db.Column(db.String(256), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))  # 所属用户

    def to_json(self):
        return {
            "id": self.id,
            "name": self.name,
            "phone": self.phone,
            "address": self.address,
            "user_id": self.user_id
        }

